package com.zzh.dynamic;

import java.util.Arrays;

public class KnapsackProblem {
    public static void main(String[] args) {
        int[] w = {1, 4, 3};
        int[] val = {1500, 3000, 2000};
        int m = 4;
        int n = val.length;
        //v[i][j]表示在前i个物品中能够装入容量为j的背包中的最大价值
        int[][] v = new int[n + 1][m + 1];
        int[][] index = new int[n + 1][m + 1];
        //初始化第一行和第一列
        for (int i = 0; i < v.length; i++) {
            v[i][0] = 0;
        }
        Arrays.fill(v[0], 0);


        for (int i = 1; i < v.length; i++) {
            for (int j = 1; j < v[0].length; j++) {
                if (w[i - 1] > j) {
                    v[i][j] = v[i - 1][j];
                } else {
                    /*对这句话的理解
                     * 从上一个和当前价值+上一个中剩余可装的选取最大的那个
                     * */
//                    v[i][j] = Math.max(v[i - 1][j], val[i - 1] + v[i - 1][j - w[i - 1]]);
                    if (v[i - 1][j] > val[i - 1] + v[i - 1][j - w[i - 1]]) {
                        v[i][j] = v[i - 1][j];
                    } else {
                        index[i][j] = 1;
                        v[i][j] = val[i - 1] + v[i - 1][j - w[i - 1]];
                    }
                }
            }
        }
        //打印v
        for (int[] i : v) {
            System.out.println(Arrays.toString(i));
        }
        System.out.println("============================");
        for (int[] i : index) {
            System.out.println(Arrays.toString(i));
        }

        int i = v.length - 1;
        int j = v[0].length - 1;
        while (j > 0 && i > 0) {
            if (index[i][j] == 1) {
                System.out.println(i);
                j -= w[i - 1];
            }
            i--;
        }


    }
}
